package com.hyd.tweet.xmpp;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.PresenceShow;
import com.google.appengine.api.xmpp.PresenceType;
import com.google.appengine.api.xmpp.Subscription;
import com.google.appengine.api.xmpp.SubscriptionType;
import com.hyd.tweet.user.UserManager;
import com.hyd.tweet.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * (description)
 *
 * @author yiding.he
 */
public class XMPPSubscriptionServlet extends HttpServlet {

    private static final Logger logger =
            Logger.getLogger(XMPPSubscriptionServlet.class.getName());

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        
        Subscription subscription = XMPPUtils.getXMPP().parseSubscription(req);
        SubscriptionType type = subscription.getSubscriptionType();
        
        if (type == SubscriptionType.UNSUBSCRIBE || type == SubscriptionType.UNSUBSCRIBED) {
            JID jid = subscription.getFromJid();
            String account = StringUtils.getAccontFromJID(jid);
            UserManager.deleteUser(account);
            logger.log(Level.INFO, "用户 " + account + " 已经退出聊天，授权信息被删除。");
            
        } else if (type == SubscriptionType.SUBSCRIBE || type == SubscriptionType.SUBSCRIBED) {
            JID jid = subscription.getFromJid();
            XMPPUtils.getXMPP().sendPresence(jid, PresenceType.AVAILABLE, PresenceShow.CHAT, "发送 /help 查看命令列表。");
            logger.log(Level.INFO, "用户 " + jid + " 已经注册本机器人。");
        }
    }
}
